package work20241223;

/**
 * @author zdl
 * @date 2024/12/23
 */
// 死锁
class Printer implements Runnable{
    private boolean flag;
    private Object obj1;
    private Object obj2;

    public Printer(boolean flag, Object obj1, Object obj2) {
        this.flag = flag;
        this.obj1 = obj1;
        this.obj2 = obj2;
    }

    @Override
    public void run() {
        if (flag){
            synchronized (obj1){
                System.out.println(Thread.currentThread().getName()+"-----> 上锁");
                synchronized (obj2){
                    System.out.println(Thread.currentThread().getName()+"-----> 上锁");
                }
            }
        }
        if (!flag){
            synchronized (obj2){
                System.out.println(Thread.currentThread().getName()+"-----> 上锁");
                synchronized (obj1){
                    System.out.println(Thread.currentThread().getName()+"-----> 上锁");
                }
            }
        }
    }
}
public class Demo6 {
    public static void main(String[] args) {
        Printer printer1 = new Printer(true, "线程1:", "线程2");
        Printer printer2 = new Printer(false, "线程1:", "线程2");
        new Thread(printer1,"线程1:").start();
        new Thread(printer2,"线程2:").start();
    }
}
